package de.haw.shc.Szenario;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import de.haw.shc.Action.Action_Impl;
import de.haw.shc.JSONObjects.Szene;
import de.haw.shc.Szenario.TimerSzenario.TimerAbotDialog;
import de.haw.shc.R;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created with IntelliJ IDEA.
 * User: mizus
 * Date: 29.06.13
 * Time: 16:29
 * To change this template use File | Settings | File Templates.
 */
public class WakeUpSzenario extends Fragment {
	
	public interface WakeupAbotDialog{
		public void showWakeupAbortDialog(MediaPlayer mediaPlayer);
	}

    private TimePicker timerPicker;
    private Button btn_wakeUP;
    private MediaPlayer mediaPlayer;
    private Timer timer;
    private SzenarioNotifyHandler notifyHandler;
    private Szene szene;
    WakeupAbotDialog wAbortDialog;


    public WakeUpSzenario(){
    }
    
    @Override
	public void onAttach(Activity activity){
		super.onAttach(activity);
		try{
			wAbortDialog = (WakeupAbotDialog) activity;
		}catch(ClassCastException e){
			throw new ClassCastException(activity.toString()+" must implement WakeupAbotDialog Interface");
		}
	}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View tView = inflater.inflate(R.layout.szenario_wakeup, container, false);

        szene = new Szene(getString(R.string.szene_wakeup));

        mediaPlayer = MediaPlayer.create(this.getActivity(), R.raw.wakup);

        DateFormat.is24HourFormat(getActivity());
        timerPicker = (TimePicker) tView.findViewById(R.id.timerpicker_wackup);
        timerPicker.setIs24HourView(DateFormat.is24HourFormat(getActivity()));
        btn_wakeUP = (Button) tView.findViewById(R.id.btn_wakeup);
        btn_wakeUP.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);

        btn_wakeUP.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(timer != null){
                    timer.cancel();
                    timer = null;
                    btn_wakeUP.setText("");
                }
            }
        });


        Button btn_ok = (Button)tView.findViewById(R.id.btn_wackup_ok);
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    action();
                } catch (ParseException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
        });
        return tView;
    }


     void action() throws ParseException{
          if(timer == null){
              notifyHandler = new SzenarioNotifyHandler(szene, wAbortDialog, mediaPlayer);
              int hour = timerPicker.getCurrentHour();
              int min = timerPicker.getCurrentMinute();

              btn_wakeUP.setText(timerPicker.getCurrentHour() + " : " + timerPicker.getCurrentMinute());

              SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");

              String dateformat = df.format(new Date());
              String  year = dateformat.split("-")[0];
              String  month = dateformat.split("-")[1];

              String day = dateformat.split("-")[2].split(" ")[0];

              Date tmpDate = df.parse(year+"-"+month+"-"+day + " "+ hour + ":" + min) ;

              int iDay = Integer.valueOf(day).intValue();

              Date wakeUpDate = null;


              if (new Date().before(tmpDate)){
                  wakeUpDate = df.parse(year+"-"+month+"-"+day + " "+ hour + ":" + min);
              }  else{
                  wakeUpDate = df.parse(year+"-"+month+"-"+ (iDay+1) + " "+ hour + ":" + min);
              }
              timer = new Timer("Wakeup");

              timer.schedule(new Task(mediaPlayer, btn_wakeUP, notifyHandler), wakeUpDate);
              Log.d("wakeUpDate: ", ""+wakeUpDate);
          }
     }

//    public WakeUpSzenario(Bundle bundle) {
//        //To change body of created methods use File | Settings | File Templates.
//    }

    public class Task extends TimerTask{

        private MediaPlayer mediaPlayer;
        private SzenarioNotifyHandler notifyHandler;

        public Task(MediaPlayer player, TextView textView, SzenarioNotifyHandler notifyHandler){
            mediaPlayer = player;
            this.notifyHandler = notifyHandler;
        }


        @Override
        public void run(){
            if (!mediaPlayer.isPlaying()){
                mediaPlayer.start();
                notifyHandler.sendEmptyMessage(SzenarioNotifyHandler.WAKEUP);
            }
        }




    }


}

